import os
from SAO_tool import SauceNAO_Picture
from pixiv_tool import Pixiv_Picture,Pixiv_Piclist
import random
import time
import webtool
import json

ppl = Pixiv_Piclist()

def Read_pictures():
    home_addr = os.getcwd()
    workingspace_addr = home_addr + "\\工程文件夹"
    filenames = os.listdir(workingspace_addr)
    
    pictures = []
    for fname in filenames:
        if fname[-3:] == "jpg" or fname[-3:] == "png"  :
            faddr = workingspace_addr + "\\" + fname
            pictures.append((fname,faddr))
    return pictures

def Auto_Download(pictures):
    for picture in pictures:
        sp = SauceNAO_Picture(pic_name = picture[0], pic_addr = picture[1])
        sp.find_saucenao()
        if sp.result:
            sp.print_saucenao_picture()
            if sp.service_name == "pixiv":
                pp = Pixiv_Picture(pid = sp.illust_id,name = sp.pic_name )
                pp.download()
                slptime = random.randint(5,10)
                print(f"下载间隔时间为{slptime}s\n")
                time.sleep(slptime)
                
    print("已全部下载完成")

def Half_Auto_Identify(pictures):
    pixiv_piclist = []
    sum_num = len(pictures)
    num = 0
    for picture in pictures:
        sp = SauceNAO_Picture(pic_name = picture[0], pic_addr = picture[1])
        sp.find_saucenao()
        if sp.result:
            sp.print_saucenao_picture()
            if sp.service_name == "pixiv":
                pixiv_piclist.append(sp.__dict__)
                num+=1
    print(f"\n\n全部查找完成,图片总数为{sum_num}，共有{num}来自pixiv:")

    ppl.writelist(piclist = pixiv_piclist)
    ppl.printwholelist()
    

def Half_Auto_Pull_Pictures(num):
    for pic in ppl.readlist(num = num):
        pp = Pixiv_Picture(pid = pic["illust_id"],name = pic["pic_name"] )
        pp.download()
        slptime = random.randint(5,10)
        print(f"下载间隔时间为{slptime}s\n")
        time.sleep(slptime)
    print("已全部下载完成")


def Half_Auto_Download(pictures):
    cmd = input("是否已获得全部图片的ID信息？1.是 2.否\n")
    num = 0
    if cmd == "2":
        input("即将检索图片ID，建议关闭全局代理，输入任意文字继续\n")
        Half_Auto_Identify(pictures)
    elif cmd == "1":
        num = int(input("请输入已下载图片数量：\n"))
        ppl.printthislist(num)
    input("即将下载原图，请打开全局代理，输入任意文字继续\n")
    Half_Auto_Pull_Pictures(num)

    
''':
    pixiv_piclist = []
    sum_num = len(pictures)
    num = 0
    input("请关闭全局代理，输入任意文字继续\n")
    for picture in pictures:
        sp = SauceNAO_Picture(picture)
        sp.find_saucenao()
        if sp.result:
            sp.print_saucenao_picture()
            if sp.service_name == "pixiv":
                pixiv_piclist.append(sp.__dict__)
                num+=1
    print(f"\n\n全部查找完成,图片总数为{sum_num}，共有{num}来自pixiv:")
    for pic in pixiv_piclist:
        print(pic["pic_name"]+" = "+pic["illust_id"])

    input("请打开全局代理，输入任意文字继续\n")
    for pic in pixiv_piclist:
        pp = Pixiv_Picture(pid = pic["illust_id"],name = pic["pic_name"] )
        pp.download()
        slptime = random.ranint(1,5)
        print(f"下载间隔时间为{slptime}s\n")
        time.sleep(slptime) 

    print("已全部下载完成")
'''            

def Hand_CTRL():
    fname = input("请输入文件名或pid\n")
    if fname[-3:] == "jpg" or fname[-3:] == "png"  :
        faddr = os.getcwd() + "\\工程文件夹\\" + fname
        sp = SauceNAO_Picture(pic_name = fname, pic_addr = faddr)
        sp.find_saucenao()
        sp.print_saucenao_picture()
        if sp.service_name == "pixiv":
            pp = Pixiv_Picture(pid = sp.illust_id,name = sp.pic_name )
            input("请打开全局代理，输入任意文字继续\n")
            pp.download()
                    
        else:
            print("非piciv图片,升级失败")
    else:
        pp = Pixiv_Picture(pid = fname,name = f"{fname}.jpg" )
        input("请打开全局代理，输入任意文字继续\n")
        pp.download()
        print("已全部下载完成")
            

if __name__ == '__main__':
    webtool.api_key = input("请输入SauceNAO的api_key:\n")
    mood = input("请输入本次的模式：1.全自动模式 2.半自动模式 3.手动模式 0.退出\r\n")
    pic_list = Read_pictures()
    print(f"工程文件夹内共有{len(pic_list)}张图片")
    if mood == '1':
        Auto_Download(pic_list)
        pass
    
    elif mood == '2':
        Half_Auto_Download(pic_list)
        pass
    
    elif mood == '3':
        while True:
            Hand_CTRL()
            if input("是否退出？ 0：退出 1：继续\n")=="0" :
                break
        pass
    elif mood == "0":
        pass
    print("程序结束，欢迎下次使用")
    
    
